#!/bin/bash

# 系统备份脚本
# 备份数据库、代码和配置文件

set -e

BACKUP_DIR="/opt/backups/nanchang-tour"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME="nanchang-tour-backup-$DATE"

mkdir -p "$BACKUP_DIR"

echo "========================================"
echo "  系统备份"
echo "========================================"
echo ""
echo "备份目录: $BACKUP_DIR"
echo "备份名称: $BACKUP_NAME"
echo ""

# 1. 备份数据库
echo "[1/4] 备份数据库..."
if [ -f "/opt/nanchang-tour/backend/.env" ]; then
    source /opt/nanchang-tour/backend/.env 2>/dev/null || true
    DB_NAME=${DB_NAME:-nanchang_tour}
    DB_USER=${DB_USER:-root}
    DB_PASSWORD=${DB_PASSWORD:-123456}
    DB_HOST=${DB_HOST:-localhost}
    
    mysqldump -u"$DB_USER" -p"$DB_PASSWORD" -h"$DB_HOST" "$DB_NAME" > "$BACKUP_DIR/$BACKUP_NAME.sql"
    echo "✓ 数据库备份完成: $BACKUP_DIR/$BACKUP_NAME.sql"
else
    echo "⚠ 无法读取数据库配置，跳过数据库备份"
fi

# 2. 备份代码
echo "[2/4] 备份代码..."
tar -czf "$BACKUP_DIR/$BACKUP_NAME-code.tar.gz" \
    --exclude='venv' \
    --exclude='node_modules' \
    --exclude='__pycache__' \
    --exclude='*.pyc' \
    --exclude='.git' \
    -C /opt nanchang-tour 2>/dev/null || true
echo "✓ 代码备份完成: $BACKUP_DIR/$BACKUP_NAME-code.tar.gz"

# 3. 备份配置文件
echo "[3/4] 备份配置文件..."
mkdir -p "$BACKUP_DIR/$BACKUP_NAME-config"
cp /opt/nanchang-tour/backend/.env "$BACKUP_DIR/$BACKUP_NAME-config/" 2>/dev/null || true
cp /etc/nginx/sites-available/nanchang-tour "$BACKUP_DIR/$BACKUP_NAME-config/nginx.conf" 2>/dev/null || true
cp /etc/systemd/system/nanchang-tour.service "$BACKUP_DIR/$BACKUP_NAME-config/" 2>/dev/null || true
tar -czf "$BACKUP_DIR/$BACKUP_NAME-config.tar.gz" -C "$BACKUP_DIR" "$BACKUP_NAME-config"
rm -rf "$BACKUP_DIR/$BACKUP_NAME-config"
echo "✓ 配置文件备份完成: $BACKUP_DIR/$BACKUP_NAME-config.tar.gz"

# 4. 备份媒体文件（如果有）
echo "[4/4] 备份媒体文件..."
if [ -d "/opt/nanchang-tour/backend/media" ]; then
    tar -czf "$BACKUP_DIR/$BACKUP_NAME-media.tar.gz" \
        -C /opt/nanchang-tour/backend media
    echo "✓ 媒体文件备份完成: $BACKUP_DIR/$BACKUP_NAME-media.tar.gz"
else
    echo "⚠ 媒体文件目录不存在，跳过"
fi

# 清理旧备份（保留最近7天）
echo ""
echo "清理旧备份（保留最近7天）..."
find "$BACKUP_DIR" -name "nanchang-tour-backup-*" -mtime +7 -delete
echo "✓ 清理完成"

echo ""
echo "========================================"
echo "  ✓ 备份完成！"
echo "========================================"
echo ""
echo "备份文件:"
ls -lh "$BACKUP_DIR/$BACKUP_NAME"* 2>/dev/null || true
echo ""

